package kryptoBlatt2;

import java.util.Arrays;

//LSR Funktion
public class Function implements IFunction<Integer, Integer>{
	
	//Koeffizienten der LSR Funktion
	private int[] coeffs;

	public Function(int[] coeffs) {
		for (int i = 0; i < coeffs.length; i++) {
			coeffs[i] = mod(coeffs[i], 2);
		}
		this.coeffs = coeffs;
	}

	//Koeffizienten ausgeben, erst die Notation, dann die Koeffizienten selbst
	public void printCoeffs(){
		if(this.coeffs != null){
			String acc2 = "[";
			int length = coeffs.length;
			for (int i = 0; i < length - 1; i++) {
				acc2 += "x" + (length - i - 1) + ", ";
			}
			acc2 += "x" + 0 + "]";
			String acc = Arrays.toString(this.coeffs);
			System.out.println("Koeffizienten: " + acc2);
			System.out.println("Koeffizienten: " + acc + "\n");
		}
	}

	//LSR Funktion anwenden
	public Integer apply(Integer... x) {
		int length = this.coeffs.length;
		int sum = sumWithCoeffs(0 , length -1, x, coeffs);
		return mod(sum, 2);
	}
	
	//Summe mit Multiplikationskoeffizienten
	private int sumWithCoeffs(int start, int stop, Integer[] vals, int[] coeffs){
		int acc = 0;
		for (int i = start; i <= stop; i++) {
			acc += vals[i] * coeffs[i];
		}
		return acc;
	}
	
	
	//Modulo Funktion
	private int mod(int val, int mod){
		int acc = val;
		while(acc < 0){
			acc += mod;
		}
		while(acc >= mod){
			acc -= mod;
		}
		return acc;
	}
	
	//Funktion klonen
	public Function clone(){
		int[] coefficients = this.coeffs.clone();
		return new Function(coefficients);
	}
			
}
